<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInst } from 'naive-ui';
import { useMessage, NButton, NCard, NForm, NFormItem, NInput } from 'naive-ui';
import { login } from '../api/user';
import statusCode from '../api/statusCode';
import { setToken } from '../util/token';
import { listAllError } from '../util/handler';

const router = useRouter();

const formRef = ref<FormInst | null>(null);
const message = useMessage();

const formValue = reactive({
  username: '',
  password: ''
});

const rules = {
  username: {
    required: true,
    message: '请输入用户名',
    trigger: 'blur'
  },
  password: {
    required: true,
    message: '请输入密码',
    trigger: 'input'
  }
};

const formValidate = async () => {
  return await formRef.value?.validate();
};

const handleLoginButtonClick = async () => {
  try {
    await formValidate();

    try {
      const resp = await login(formValue);

      if (resp.status === statusCode.SUCCESS) {
        setToken(resp.data);
        message.success('登录成功', {
          duration: 1200,
          onAfterLeave: () => {
            if (router.currentRoute.value.query.redirect) {
              router.replace(router.currentRoute.value.query.redirect as string);
            } else {
              router.replace({ name: 'index' });
            }
          }
        });
      } else if (resp.status === statusCode.INCORRECT_USERNAME_OR_PASSWORD) {
        message.error('账号或密码错误');
      } else {
        throw new Error(`错误码 ${resp.status}`);
      }
    } catch (error) {
      message.error("" + error);
    }

  } catch (errors) {
    if (errors instanceof Array) {
      listAllError(errors, message);
    } else {
      throw errors;
    }
  }
};

const handleRegisterButtonClick = () => {
  router.push({ path: '/register' })
};
</script>

<template>
  <n-card>
    <n-form
      :model="formValue"
      :rules="rules"
      :show-require-mark="false"
      ref="formRef"
    >
      <n-form-item
        label="用户名"
        path="username"
      >
        <n-input
          v-model:value="formValue.username"
          placeholder="用户名"
        />
      </n-form-item>
      <n-form-item
        label="密码"
        path="password"
      >
        <n-input
          type="password"
          v-model:value="formValue.password"
          placeholder="密码"
          :maxlength="16"
        />
      </n-form-item>
      <n-form-item>
        <n-button
          @click="handleLoginButtonClick"
          type="primary"
          attr-type="submit"
        >
          登录
        </n-button>
        <n-button
          @click="handleRegisterButtonClick"
          attr-type="button"
        >
          注册
        </n-button>
      </n-form-item>
    </n-form>
  </n-card>
</template>

<style scoped>
</style>
